package com.dianshan.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dianshan.entity.Address;
import com.dianshan.entity.dto.AddressDto;
import com.dianshan.mapper.AddressMapper;
import com.dianshan.service.IAddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.domain.PageQuery;
import com.domain.PageResult;
import com.exception.CommonException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaolong
 * @since 2024-06-18
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements IAddressService {

    @Autowired
    AddressMapper addressMapper;

    @Override
    public PageResult<Address> listOne(PageQuery pageQuery) {


        Page<Address> page = pageQuery.toMpPage();

        Page<Address> addressPage = page(page);

        return PageResult.of(addressPage,address -> BeanUtil.copyProperties(address,Address.class));

    }

    @Override
    public AddressDto updateAddress(Address address) {

        if (addressMapper.updateById(address) <= 0){
            throw new CommonException("更新地址失败,请重试");
        }

        return selectAddress(address.getId());
    }

    @Override
    public void deleteAddress(Long id) {
        boolean b = removeById(id);
        if (!b){
            throw new CommonException("删除地址失败,请重试");
        }

    }

    @Override
    public void appendAddress(Address address) {

        if (addressMapper.insert(address) <=0 ){
            throw new CommonException("删除地址失败,请重试");
        }

    }

    @Override
    public AddressDto selectAddress(Long id) {

        Address addressOne = getById(id);

        AddressDto addressDto = new AddressDto();

        BeanUtils.copyProperties(addressOne,addressDto);

        return addressDto;

    }

    @Override
    public void setDefault(Address address) {
        LambdaUpdateWrapper<Address> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Address::getUserId,address.getUserId())
                .set(Address::getIsDefault,0);

        addressMapper.update(null,wrapper);

        if (addressMapper.updateById(address) <= 0){
            throw new CommonException("删除地址失败,请重试");
        }


    }


}
